package com.soujiayi.activity;


import java.util.HashMap;

import com.soujiayi.net.HttpRequester;
import com.soujiayi.net.NetworkUtils;
import com.soujiayi.store.DatabaseManager;
import com.soujiayi.util.CommonUtils;
import com.soujiayi.util.Constants;
import com.soujiayi.util.UserKeeper;
import com.soujiayi.weibo.User;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Toast;

public class RegisterActivity extends Activity {

	private EditText address;
	private EditText name;
	private EditText password;
	private ScrollView scrollView;
	private Button clearEmailAddressBtn;
	private Button clearNameBtn;
	private Button clearPasswordBtn;
	private int green;
	private int red;
	private boolean isAddressValid = false;
	private boolean isNameValid = false;
	private boolean isPasswordValid = false;
	
	private DatabaseManager databaseManager = new DatabaseManager(RegisterActivity.this);
	
	private ProgressDialog progressDialog ;
    private HttpRequester httpRequester;
    private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		((MyApplication) this.getApplication()).addActivity(this);
		setContentView(R.layout.register);

		green = this.getResources().getColor(R.color.green);
		red = this.getResources().getColor(R.color.red1);
		clearEmailAddressBtn = (Button) findViewById(R.id.register_clear_email_address);
		clearNameBtn = (Button) findViewById(R.id.register_clear_name);
		clearPasswordBtn = (Button) findViewById(R.id.register_clear_password);
		
		address = (EditText) findViewById(R.id.register_email_address);
		address.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				clearEmailAddressBtn.setVisibility(s.toString().equals("") ? View.GONE
						: View.VISIBLE);
				
				if(CommonUtils.isEmailAddress(s.toString())){
					address.setTextColor(green);
					isAddressValid = true;
				}else{
					address.setTextColor(red);
					isAddressValid = false;
				}
			}
		});

		name = (EditText) findViewById(R.id.register_name);
		name.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				clearNameBtn.setVisibility(s.toString().equals("") ? View.GONE
						: View.VISIBLE);
				
				if(CommonUtils.isCorrectName(s.toString())){
					name.setTextColor(green);
					isNameValid = true;
				}else{
					name.setTextColor(red);
					isNameValid = false;
				}
			}
		});

		password = (EditText) findViewById(R.id.register_password);
		password.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				clearPasswordBtn
						.setVisibility(s.toString().equals("") ? View.GONE
								: View.VISIBLE);
				
				if(5 <= s.toString().length() && s.toString().length() <= 36){
					password.setTextColor(green);
					isPasswordValid = true;
				}else{
					password.setTextColor(red);
					isPasswordValid = false;
				}
			}
		});

		scrollView = (ScrollView) findViewById(R.id.register_scrollview);
		scrollView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(name.getWindowToken(), 0);
				imm.hideSoftInputFromWindow(password.getWindowToken(), 0);
				imm.hideSoftInputFromWindow(clearEmailAddressBtn.getWindowToken(), 0);
				clearNameBtn.setVisibility(View.GONE);
				clearPasswordBtn.setVisibility(View.GONE);
				clearEmailAddressBtn.setVisibility(View.GONE);
				return false;
			}
		});
		
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Bundle data = msg.getData();
                progressDialog.dismiss();
                boolean isError = data.getBoolean(Constants.IS_ERROR, false);
                if(isError){
                	Toast.makeText(RegisterActivity.this,RegisterActivity.this.getResources().getString(R.string.register_failure),Toast.LENGTH_LONG).show();
                }else{
                	int uid = (Integer) msg.obj;
                	if(uid > 0){
                		Toast.makeText(RegisterActivity.this,RegisterActivity.this.getResources().getString(R.string.register_success),Toast.LENGTH_LONG).show();
            			User user = new User();
            			user.setType(Constants.USER_TYPE_SOUJIAYI);
            			user.setUid(uid);
            			user.setUsername(name.getText().toString());
            			user.setPassword(password.getText().toString());
            			user.setEmail(address.getText().toString());
            			user.setNickname(name.getText().toString());
            			user.setGender("1");
            			user.setBirthday("19880101");
            			databaseManager.insertUser(user);
            			
            			UserKeeper.keepUser(RegisterActivity.this, user, Constants.PREFERENCES_NAME_USER);
            			Intent intent = new Intent(RegisterActivity.this,UserCenterActivity.class);
            			startActivity(intent);
            			RegisterActivity.this.finish();
            			overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                	}else if(uid == -1){
                		Toast.makeText(RegisterActivity.this, RegisterActivity.this.getResources().getString(R.string.register_username_exist),Toast.LENGTH_LONG).show();
                	}else if(uid == -2){
                		Toast.makeText(RegisterActivity.this,RegisterActivity.this.getResources().getString(R.string.register_email_exist),Toast.LENGTH_LONG).show();
                	}
                }
            }
        };
               
        httpRequester = new HttpRequester(this,1, handler);
	}

	public void back(View view) {
		this.finish();
		overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
	}

	public void clearEmailAddress(View view) {
		address.setText("");
		clearEmailAddressBtn.setVisibility(View.GONE);
	}
	
	public void clearName(View view) {
		name.setText("");
		clearNameBtn.setVisibility(View.GONE);
	}

	public void clearPassword(View view) {
		password.setText("");
		clearPasswordBtn.setVisibility(View.GONE);
	}

	public void register(View view) {
		if(isAddressValid && isNameValid && isPasswordValid){
			if(!NetworkUtils.isNetworkConnected(this)){
				Toast.makeText(
						RegisterActivity.this,
						RegisterActivity.this
								.getString(R.string.network_unavailable_message),
						Toast.LENGTH_LONG).show();
				return;
			}
			
			progressDialog = new ProgressDialog(RegisterActivity.this);
			progressDialog.setMessage(getResources().getString(R.string.register_loading));
			progressDialog.setCancelable(false);
		    progressDialog.show();
		    
            HashMap<String, String> parameters = new HashMap<String, String>();
            parameters.put("sid", ((MyApplication)this.getApplication()).getSessionId());
            parameters.put("email", address.getText().toString());
            parameters.put("username", name.getText().toString());
            parameters.put("passwd", password.getText().toString());
            httpRequester.register(parameters);
		}
	}
	
	@Override
	protected void onDestroy() {
		databaseManager.closeDB();
		if(httpRequester != null){
			httpRequester.close();
		}
		super.onDestroy();
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
			return false;
		}
		return false;
	}

}
